#!./bin/python
# ----------------------------------------------------------------------
# Compile pyx files
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------

# Python modules
import os
import subprocess
import stat
from noc.config import config

CYTHONIZE = config.path.cythonize


def main():
    # Check cythonize is exists and executable
    if not os.path.isfile(CYTHONIZE) or not os.access(CYTHONIZE, os.X_OK):
        print("ERROR")
        return
    #
    changed = False
    for path, dirs, files in os.walk("speedup"):
        for f in files:
            if not f.endswith(".pyx"):
                continue
            pyx_path = os.path.join(path, f)
            so_path = pyx_path[:-4] + ".so"
            if (
                not os.path.exists(so_path) or
                os.stat(pyx_path)[stat.ST_MTIME] > os.stat(so_path)[stat.ST_MTIME]
            ):
                try:
                    null = open("/dev/null", "w")
                    subprocess.check_call(
                        [CYTHONIZE, "-i", pyx_path],
                        stdout=null,
                        stderr=null
                    )
                    changed = True
                except OSError as e:
                    print("ERROR")
                    return
    if changed:
        print("CHANGED")
    else:
        print("OK")


if __name__ == "__main__":
    main()
